package com.kyzh.core.dialog

import android.annotation.SuppressLint
import android.app.Activity
import android.util.Log
import android.view.*
import android.webkit.WebSettings
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import com.gushenge.core.beans.VipQuanYiBean
import com.kyzh.core.R
import com.kyzh.core.databinding.DialogVipBinding

private var descDialog: AlertDialog?=null

fun Activity.showVipDialog(title: VipQuanYiBean, listener:()->Unit){
    descDialog = AlertDialog.Builder(this, R.style.kyzhGuestLoginDialog)
        .setView(getView(title,listener))
        .create()
    val dialogWindow: Window? = descDialog!!.window
    dialogWindow?.setBackgroundDrawableResource(android.R.color.transparent)

    val lp: WindowManager.LayoutParams? = dialogWindow?.getAttributes()
    dialogWindow?.setGravity(Gravity.CENTER)
    lp?.width = resources.displayMetrics.widthPixels // 宽度
    dialogWindow?.setAttributes(lp)
    descDialog?.show()
}
@SuppressLint("ClickableViewAccessibility")
private fun Activity.getView(title: VipQuanYiBean, listener:()->Unit): View {
    val binding = DataBindingUtil.inflate<DialogVipBinding>(
        LayoutInflater.from(this),
        R.layout.dialog_vip,null,false)
    binding.data = title
    val webSettings = binding.webView.settings
    webSettings.allowFileAccess = true// 设置允许访问文件数据
    webSettings.setSupportZoom(true)
    webSettings.builtInZoomControls = true
    webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
    webSettings.domStorageEnabled = true
    webSettings.databaseEnabled = true
    webSettings.javaScriptEnabled = true
    binding.webView.loadUrl(title.content_2)
    // 关键性代码，这里要给webview添加这行代码，才可以点击之后正常播放音频。记录一下。
    webSettings.mediaPlaybackRequiresUserGesture = false
    binding.webView.webChromeClient =object :com.tencent.smtt.sdk.WebChromeClient(){
        override fun onJsAlert(
            p0: com.tencent.smtt.sdk.WebView?,
            p1: String?,
            p2: String?,
            p3: com.tencent.smtt.export.external.interfaces.JsResult?
        ): Boolean {
            Log.e("TAG", "onJsAlert: "+p2 )
            if(p2 == "go"){
                descDialog?.dismiss()
                listener()
            }
            p3?.cancel()
            return true
        }
    }


    binding.ivClose.setOnClickListener {
        descDialog?.dismiss()
    }
    return binding.root
}